package com.imflea.zero.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.imflea.zero.constants.ZeroContant;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.util.base.JsonResult;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author zhaoyang
 * @version 1.0
 * @project farmplus-service
 * @package com.imflea.zero.utils
 * @filename RestUtil.java 创建时间: 2021/9/10
 * @description 描述（全局业务异常处理类）
 * @copyright Copyright (c) 2021 中国软件与技术服务股份有限公司
 */
public final class RestUtil {


    private static final Logger logger = LoggerFactory.getLogger(RestUtil.class);


    private RestUtil() {
        throw new IllegalStateException("Util class no instance ");
    }


    public static <T> JsonResult<T> success(T t) {
        return new JsonResult<>(ZeroContant.getSuccessCode(), "", t);
    }

    /// TODO 暂时是不需要的
///    public static <T> JsonResult<T> fail(String message) {
///        return new JsonResult<>(ZeroContant.getFailCode(), message);
///   }

    public static <T> T orElseThrow(boolean success, T t, String err) {

        if (success) {
            return t;
        }

        logger.error("业务异常,参数:{},错误原因{}", JSONUtil.toJsonStr(t), err);

        throw new BizException(err);
    }

    public static <T> T ifNullThrow(T t, String errMsg) {
        return Optional.ofNullable(t).orElseThrow(() -> new BizException(errMsg));
    }


    public static Boolean orElseThrow(boolean success, String err) {

        if (success) {
            return success;
        }

        logger.error("业务异常,错误原因{}", err);

        throw new BizException(err);
    }

    public static <T> List<T> orEmptyList(List<T> t) {

        if (CommonUtils.isNull(t)) {
            return new ArrayList<>();
        }

        return t;
    }

    public static <T> T orOther(T t, T other) {

        if (CommonUtils.isNull(t)) {
            return other;
        }

        return t;
    }

    public static <T> void settingCreator(T entity) {
        Creator creator = new Creator(SessionUtils.getUserId(), SessionUtils.getWxNickName() == null ? SessionUtils.getUserName() : SessionUtils.getWxNickName(), LocalDateTime.now());
        BeanUtil.copyProperties(creator, entity, CopyOptions.create().setPropertiesFilter((field, val) -> field.getName().equals("createUserId") || field.getName().equals("createUserName") || field.getName().equals("createTime")));
    }

    public static <T> void settingUpdator(T entity) {
        Updator updator = new Updator(SessionUtils.getUserId(), SessionUtils.getWxNickName() == null ? SessionUtils.getUserName() : SessionUtils.getWxNickName(), LocalDateTime.now());
        BeanUtil.copyProperties(updator, entity, CopyOptions.create().setPropertiesFilter((field, val) -> field.getName().equals("updateUserId") || field.getName().equals("updateUserName") || field.getName().equals("updateTime")));
    }

    @Getter
    private static class Creator {

        private LocalDateTime createTime;

        private String createUserName;

        private String createUserId;

        public Creator(String createUserId, String createUserName, LocalDateTime createTime) {
            this.createTime = createTime;
            this.createUserName = createUserName;
            this.createUserId = createUserId;
        }

    }


    @Getter
    private static class Updator {

        private LocalDateTime updateTime;

        private String updateUserId;

        private String updateUserName;

        public Updator(String updateUserId, String updateUserName, LocalDateTime updateTime) {
            this.updateTime = updateTime;
            this.updateUserId = updateUserId;
            this.updateUserName = updateUserName;
        }
    }
}
